<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckFlex;
use app\validate\CheckCate;
use app\validate\CheckFlexClasses;
use think\exception\ValidateException;
use think\facade\Queue;
use EasyWeChat\Factory;


// 调研管理
class Flex extends BaseController
{


    public function index()
    {
        return View::fetch();
    }



    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];


        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['title', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                $where[] = ['status', '=', $get['status']];
            }
        }


        $total = Db::name('flex')
            ->where($where)
            ->count();

        $rows = Db::name('flex')
            ->where($where)
            ->order(['status'=>'asc', 'sort' => 'asc', 'add_time'=>'desc'])
            ->field('id, title, end, start, open_up, range, add_time, sort, status')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();
        foreach ($rows as &$v) {
            $v['time'] = date('Y-m-d H:i',$v['start']).' - '. date('Y-m-d H:i',$v['end']);
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }



    // 分享二维码
    public function getQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/flex/pages/offlineList/offlineList';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);
            return $this->outputAjax('获取成功', 0, ['url' => $qr]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function downloadQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');
        $title = $request->param('title');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/flex/pages/offlineList/offlineList';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 1280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);

            $fileTmp = pathinfo($qr);
            $fileExt = $fileTmp['extension'];    //图片后缀名
            $filename = str_replace('.', '', $title);   //图片名称，可以任务设置图片名称
            $saveFileName = ($filename.'.'.$fileExt);
            $fp = fopen($qr,"r");
            //下载文件需要用到的头
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Content-Disposition: attachment; filename=".$saveFileName);
            $buffer = 1024;
            $file_count = 0;
            //向浏览器返回数据
            while (!feof($fp)) {
                $file_con = fread($fp,$buffer);
                $file_count += $buffer;
                echo $file_con;
            }
            fclose($fp);
            exit;
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function setStatus(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }
        try {
            $inf = Db::name('flex')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            if ($status == 1) {
                $flex_course = Db::name('flex_course')->where('flex_id', '=', $id)->column('courseid');

                $flex_id = Db::name('flex_course')
                    ->where('flex_id', '<>', $id)
                    ->whereIn('courseid', $flex_course)
                    ->column('flex_id');

                $flex_name = Db::name('flex')->whereIn('id', $flex_id)->where('status', '=', 1)->column('title');
                if (!empty($flex_name)) {
                    return $this->outputAjax($inf['title'].'调研与'.implode('|', $flex_name).'调研有课程重复');
                }
            }

            $update = array(
                'status' => $status,
            );
            if(Db::name('flex')->where('id', '=', $id)->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }



    public function showBackground()
    {
        return View::fetch();
    }

    public function getBackgroundList()
    {
        $arr = array(
            array(
                'name' => '背景1',
                'url' => 'https://learningspark-resource.lorealchina.com/static/background/1.png'
            ),
            array(
                'name' => '背景2',
                'url' => 'https://learningspark-resource.lorealchina.com/static/background/2.png'
            ),
            array(
                'name' => '背景3',
                'url' => 'https://learningspark-resource.lorealchina.com/static/background/3.png'
            ),
            array(
                'name' => '背景4',
                'url' => 'https://learningspark-resource.lorealchina.com/static/background/4.png'
            ),
            array(
                'name' => '背景5',
                'url' => 'https://learningspark-resource.lorealchina.com/static/background/5.png'
            ),
            array(
                'name' => '背景6',
                'url' => 'https://learningspark-resource.lorealchina.com/static/background/6.png'
            ),
        );

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $arr
        );
        return json($data);
    }

    // 更新推荐引擎学员
    public function updateCourseUser(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        if (empty($post['flex_id'])) {
            return $this->outputAjax('参数不足！');
        }

        $res = Db::name('timing')
            ->where('name', '=', 'flex更新推荐引擎')
            ->where('state', '=', 1)
            ->find();

        if ($res) {
            return $this->outputAjax('推荐引擎更新中, 请等待执行', 0);
        }


        $ts = time();

        $insert = array(
            'name' => 'flex更新推荐引擎',
            'state' => 1,
            'add_time' => $ts,
            'date' => date('Ymd', $ts),
        );

        $timing_id = Db::name('timing')->insertGetId($insert);
        if (!$timing_id) {
            return $this->outputAjax('任务添加失败[2]');
        }

        // 1.当前任务由哪个类来负责处理
        // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
        $jobHandlerClassName = 'app\job\UpdateFlexCourseUser';

        // 2.当任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName = "UpdateFlexCourseUser";

        // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
        $jobData = ['ts' => $ts, 'page' => 1, 'timing_id' => $timing_id, 'flex_id' => $post['flex_id']];

        // 4.将该任务推送到消息列表，等待对应的消费者去执行
        // 入队列，later延迟执行，单位秒，push立即执行
        $isPushedTask1 = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
        if ($isPushedTask1 !== false) {
            return $this->outputAjax('更新推荐引擎任务添加成功, 请等待执行', 0);

        } else {

            return $this->outputAjax('更新推荐引擎任务添加失败');

        }
    }

    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        return View::fetch();
    }



    //+班级保存
    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckFlex::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }
		
		if (empty($post['background_pc'])){
            return $this->outputAjax('背景pc不能为空！');
        }
        Db::startTrans();
        try {
            $t = explode(' - ',$post['time']);
            $insert = array(
                'title' => $post['title'],
                'open_up' => $post['open_up'],
                'range' => $post['range'],
                'background' => $post['background'],
				'background_pc' => $post['background_pc'],
                'icon' => $post['icon'],
                'number' => $post['number'],
                'start' => strtotime($t[0]),
                'end' => strtotime($t[1]),
                'status' => 2,
                'add_time' => time(),
                'update_time' => time(),
            );
            $flex_id = Db::name('flex')->insertGetId($insert);

            if (!$flex_id) {
                Db::rollback();
                return $this->outputAjax('创建失败！');
            }


            $db = env('database.database');
            $table = 'o_flex_course_user_'.$flex_id;
            $sql = "CREATE TABLE `$db`.`$table` (`id` INT(10) NOT NULL AUTO_INCREMENT , `courseid` VARCHAR(10) NOT NULL , `rules_id` INT(10) NOT NULL , `userid` VARCHAR(50) NOT NULL , `type` TINYINT(1) NOT NULL COMMENT '1-规则 2-直选' , `recommend_type` TINYINT(1) NOT NULL COMMENT '1-硬推荐 2-软推荐' , `add_time` INT(10) NOT NULL , PRIMARY KEY (`id`), INDEX (`courseid`, `userid`, `recommend_type`)) ENGINE = InnoDB;";
            Db::query($sql);

            Db::commit();
            return $this->outputAjax('创建成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('flex')->find($id);
        $inf['time'] = date('Y-m-d H:i:s',$inf['start']).' - '. date('Y-m-d H:i:s',$inf['end']);
        View::assign('inf',$inf);
        return View::fetch();
    }

    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckFlex::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        $flex = Db::name('flex')->where('id', '=', $post['id'])->find();
        if (!$flex) {
            return $this->outputAjax('参数错误！');
        }
		
		if (empty($post['background_pc'])){
            return $this->outputAjax('背景pc不能为空！');
        }

        Db::startTrans();
        try {
            $t = explode(' - ',$post['time']);
            $update = array(
                'id' => $post['id'],
                'title' => $post['title'],
                'open_up' => $post['open_up'],
                'range' => $post['range'],
                'background' => $post['background'],
				'background_pc' => $post['background_pc'],
                'icon' => $post['icon'],
                'start' => strtotime($t[0]),
                'end' => strtotime($t[1]),
                'update_time' => time(),
            );

            if (!Db::name('flex')->update($update)) {
                Db::rollback();
                return $this->outputAjax('保存失败！');
            }

            Db::commit();
            return $this->outputAjax('保存成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }



    //+排序
    public function sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        if (empty($post)) {
            return $this->outputAjax('参数不足！');
        }

        $res = Db::name('flex')->where('id', '=', $post['id'])->find();
        if (!$res) {
            return $this->outputAjax('参数错误！');
        }
        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }
        Db::startTrans();
        try {
            $rows = Db::name('flex')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort asc')
                ->select()
                ->toArray();

            if (!Db::name('flex')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('flex')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    // 直播课学员
    public function members(Request $request)
    {
        $flex_id = $request->get('id');
        View::assign('flex_id',$flex_id);
        return View::fetch();
    }


    public function getMembersList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $flex_id = $request->get('flex_id');
        $get = $request->get();

        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['a.userid', 'like', '%'.$get['keys'].'%'];
            }
        }


        $where[] = ['a.flex_id', '=', $flex_id];

        $total = Db::table('o_flex_range_user')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->where($where)
            ->count();

        $rows = Db::table('o_flex_range_user')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->field('a.*, b.name, b.department_name, b.division')
            ->where($where)
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                } else {
                    $v['userid'] = $v['userid'];
                }
            } else {
                $v['userid'] = $v['userid'];
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function deleteMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        $id = explode(',',trim($id,','));

        Db::startTrans();
        try {
            foreach ($id as $key => $value) {
                if (!Db::name('flex_range_user')->where('id', '=', $value)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[1]！');
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function user(Request $request)
    {
        $flex_id = $request->param('flex_id');
        View::assign('flex_id', $flex_id);
        return View::fetch();
    }

    public function saveUser(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $flex_id = $request->post('flex_id');
        $uid = $request->post('id');

        if(!$flex_id){
            return $this->outputAjax('缺少课程id！');
        }

        try {
            $uids = explode(',',$uid);
            if(!is_array($uids) || count($uids) <= 0){
                return $this->outputAjax('请选择学员！');
            }

            $t = [];
            $t['flex_id'] = $flex_id;
            $t['add_time'] = time();

            foreach ($uids as $key => $value) {
                $user = Db::name('members')
                    ->where('id', '=', $value)
                    ->field('id, userid, name')
                    ->find();
                $res = Db::name('flex_range_user')
                    ->where('userid', '=', $user['userid'])
                    ->where('flex_id', '=', $flex_id)
                    ->find();
                if($res){
                    continue;
                }
                $t['userid'] = $user['userid'];
                Db::name('flex_range_user')->insert($t);
            }
            return $this->outputAjax('添加成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //文件批量导入学员
    public function import(Request $request)
    {
        $flex_id = $request->param('flex_id');
        View::assign('flex_id', $flex_id);
        return View::fetch();
    }


    public function executeImport(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $flex_id = $request->param('flex_id');

        if(empty($flex_id)) {
            return $this->outputAjax('参数缺失', 2);
        }
        $flex = Db::name('flex')->where('id', '=', $flex_id)->find();
        if(!$flex) {
            return $this->outputAjax('调研不存在', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];

                $user = Db::name('members')
                    ->where('userid', '=', $userid)
                    ->field('id, userid, language, name')
                    ->find();
                if (!$user) {
                    continue;
                }

                $res = Db::name('flex_range_user')
                    ->where('userid', '=', $userid)
                    ->where('flex_id', '=', $flex_id)
                    ->find();
                if($res) {
                    continue;
                }

                $newValue = [
                    'flex_id' => $flex_id,
                    'add_time' => time(),
                    'userid' => $userid,
                ];
                $f = Db::name('flex_range_user')->insert($newValue);
                if ($f) {
                    $i++;
                }
            }
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }


    //文件批量导入学员
    public function importRemove(Request $request)
    {
        $flex_id = $request->param('flex_id');
        View::assign('flex_id', $flex_id);
        return View::fetch();
    }


    public function executeImportRemove(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $flex_id = $request->param('flex_id');

        if(empty($flex_id)) {
            return $this->outputAjax('参数缺失', 2);
        }
        $flex = Db::name('flex')->where('id', '=', $flex_id)->find();
        if(!$flex) {
            return $this->outputAjax('调研不存在', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];

                $user = Db::name('members')
                    ->where('userid', '=', $userid)
                    ->field('id, userid, language, name')
                    ->find();
                if (!$user) {
                    continue;
                }

                $res = Db::name('flex_range_user')
                    ->where('userid', '=', $userid)
                    ->where('flex_id', '=', $flex_id)
                    ->find();
                if(!$res) {
                    continue;
                }

                $f = Db::name('flex_range_user')
                    ->where('flex_id', '=', $flex_id)
                    ->where('userid', '=', $userid)
                    ->delete();
                if ($f) {
                    $i++;
                }
            }
            return $this->outputAjax('导入删除成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }


    // 调研数据
    public function data(Request $request)
    {
        $flex_id = $request->param('id');

        $city = Db::name('city')->select();
        View::assign('flex_id', $flex_id);
        View::assign('city', $city);
        return View::fetch();
    }

    public function getDataList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];
        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['city'])) {
            if (!empty($get['city'])) {
                $where[] = ['city', 'like', '%'.$get['city'].'%'];
            }
        }

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                $where[] = ['status', '=', $get['status']];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ',$get['time']);
                $where[] = ['update_time', 'between', [strtotime($t[0]),(strtotime($t[1])+86399)]];
            }
        }
        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['userid', 'like', '%'.$get['keys'].'%'];
            }
        }
        $where[] = ['flex_id', '=', $get['flex_id']];
        $total = Db::name('flex_user')
            ->where($where)
            ->count();

        $rows = Db::name('flex_user')
            ->where($where)
            ->order('id', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $members = Db::name('members')
                ->where('userid', '=', $v['userid'])
                ->field('id, name, division, department_name')
                ->find();
            if ($members) {
                $v['name'] = $members['name'];
                $v['department_name'] = $members['department_name'];
                $v['division'] = $members['division'];
            } else {
                $v['name'] = '--';
                $v['department_name'] = '';
                $v['division'] = '';
            }

            switch ($v['status']) {
                case 1:
                    $v['status_name'] = '<span style="color: #009688;">已完成</span>';
                    break;
                case 2:
                    $v['status_name'] = '<span style="color: #FFB800;">未完成</span>';
                    break;
            }

            if ($v['status'] != 1) {
                $v['time'] = '---------';
            } else {
                $v['time'] = date('Y-m-d H:i:s', $v['update_time']);
            }

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['carolid'] = '00'.$v['userid'];
                } else {
                    $v['carolid'] = $v['userid'];
                }
            } else {
                $v['carolid'] = $v['userid'];
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 导出选课完成情况
    public function exportData(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '选课完成情况'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '城市', '完成状态', '提交时间']);

        $where = [];
        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['city'])) {
            if (!empty($get['city'])) {
                $where[] = ['city', 'like', '%'.$get['city'].'%'];
            }
        }

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                $where[] = ['status', '=', $get['status']];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ',$get['time']);
                $where[] = ['update_time', 'between', [strtotime($t[0]),(strtotime($t[1])+86399)]];
            }
        }
        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['userid', 'like', '%'.$get['keys'].'%'];
            }
        }
        $where[] = ['flex_id', '=', $get['flex_id']];



        //链接数据库
        $total = Db::name('flex_user')
            ->where($where)
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::name('flex_user')
                ->where($where)
                ->order('id', 'desc')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {
                $members = Db::name('Members')
                    ->where('userid', '=', $v['userid'])
                    ->field('id, name, division, department_name')
                    ->find();
                $name = $members['name'];
                $department_name = $members['department_name'];
                $division = $members['division'];

                switch ($v['status']) {
                    case 1:
                        $status_name = '已完成';
                        break;
                    case 2:
                        $status_name = '未完成';
                        break;
                }

                if ($v['status'] != 1) {
                    $time = '---------';
                } else {
                    $time = date('Y-m-d H:i:s', $v['update_time']);
                }

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $carolid = "'00".$v['userid'];
                    } else {
                        $carolid = $v['userid'];
                    }
                } else {
                    $carolid = $v['userid'];
                }

                $arr = [
                    $carolid,
                    $name,
                    $division,
                    $department_name,
                    $v['city'],
                    $status_name,
                    $time
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }


    // 导出选课详情
    public function exportDataView(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();

        set_time_limit(0);
        ob_end_clean ();
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '选课详情'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', '部门', '地区', '属性', '课程ID', '课程名称', '班级名称', '开课时间', '是否包含在选课列表']);

        $where = [];
        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['city'])) {
            if (!empty($get['city'])) {
                $where[] = ['city', 'like', '%'.$get['city'].'%'];
            }
        }

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                $where[] = ['status', '=', $get['status']];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ',$get['time']);
                $where[] = ['update_time', 'between', [strtotime($t[0]),(strtotime($t[1])+86399)]];
            }
        }
        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['userid', 'like', '%'.$get['keys'].'%'];
            }
        }
        $where[] = ['flex_id', '=', $get['flex_id']];
        //$where[] = ['status', '=', 1];


        //链接数据库
        $total = Db::name('flex_user')
            ->where($where)
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::name('flex_user')
                ->where($where)
                ->order('id', 'desc')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$value) {
                $a = Db::name('tna_data')
                    ->where('flex_id', '=', $value['flex_id'])
                    ->where('userid', '=', $value['userid'])
                    ->where('status', '=', 1)
                    ->where('type', 'in', ['must','ia'])
                    ->column('courseid');
                $course_data = [];
                array_push($course_data, $value['courseid']);

                $arr = array_merge($a,$course_data);
                $temp = Db::name('course')->where('courseid', 'in', $arr)->select()->toArray();
                if ($temp) {
                    foreach ($temp as $k => $v) {
                        $class_id = Db::name('flex_user_classes')
                            ->where('flex_id', '=', $get['flex_id'])
                            ->where('courseid', '=', $v['courseid'])
                            ->where('userid', '=', $value['userid'])
                            ->value('class_id');

                        $class_name = Db::name('flex_classes')
                            ->where('id', '=', $class_id)
                            ->where('flex_id', '=', $get['flex_id'])
                            ->field('name, class_time')
                            ->find();

                        $find = Db::name('course_user')
                            ->where('courseid', '=', $v['courseid'])
                            ->where('recommend_type', '=', 2)
                            ->where('userid', '=', $value['userid'])
                            ->find();
                        if ($find) {
                            $contain = '是';
                        } else {
                            $contain = '否';
                        }
                        $count = mb_strlen($value['userid']);
                        if ($count == 6) {
                            if (is_numeric($value['userid'])) {
                                $carolid = "'00".$value['userid'];
                            } else {
                                $carolid = $value['userid'];
                            }
                        } else {
                            $carolid = $value['userid'];
                        }

                        $department_name = Db::name('Members')->where('userid', '=', $value['userid'])->value('department_name');

                        $arr = [
                            $carolid,
                            $value['name'],
                            $department_name,
                            $value['city'],
                            get_config('app.course.type',$v['type']),
                            $v['courseid'],
                            $v['e_seminar'] == ''?$v['seminar']:$v['e_seminar'],
                            $class_name['name'],
                            $class_name['class_time'],
                            $contain
                        ];
                        fputcsv($fp, $arr);
                    }
                }
            }
            //每1千条数据就刷新缓冲区
            flush();
        }
    }


    //删除调研数据
    public function deleteData(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        if (!$post) {
            return $this->outputAjax('参数不足！');
        }
        $ids = explode(',', $post['id']);
        Db::startTrans();

        try {
            foreach ($ids as &$v) {
                $res = Db::name('flex_user')->where('id', '=', $v)->find();

                if (!Db::name('flex_user')->where('id', '=', $v)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败！');
                }
                $res = Db::name('flex_user_classes')
                    ->where('userid', '=', $res['userid'])
                    ->where('courseid', '=', $res['courseid'])
                    ->where('flex_id', '=', $post['flex_id'])
                    ->find();
                if ($res) {
                    if (!Db::name('flex_user_classes')
                        ->where('userid', '=', $res['userid'])
                        ->where('courseid', '=', $res['courseid'])
                        ->where('flex_id', '=', $post['flex_id'])
                        ->delete()) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[1]');
                    }
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    //学员调研详情
    public function dataView(Request $request)
    {
        $flex_id = $request->get('flex_id');
        $userid = $request->get('userid');

        View::assign('flex_id', $flex_id);
        View::assign('userid', $userid);

        return View::fetch();
    }


    public function getDataViewList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $flex_id = $request->get('flex_id');
        $userid = $request->get('userid');

        if(!$flex_id || !$userid){
            return json(['code'=>'500','msg'=>'参数不足！','data'=>[]]);
        }


        $rows = Db::name('flex_user_classes')
            ->where('flex_id', '=', $flex_id)
            ->where('userid', '=', $userid)
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $course = Db::name('course')
                ->where('courseid', '=', $v['courseid'])
                ->field('e_seminar, seminar')
                ->find();
            if ($course['e_seminar'] == '') {
                $title = $course['seminar'];
            } else {
                $title = $course['e_seminar'];
            }
            $v['title'] = $title;

            $class_name = Db::name('flex_classes')
                ->where(array('id'=>$v['class_id'],'flex_id'=>$v['flex_id']))
                ->field('name, e_name')
                ->find();

            $v['class_name'] = $class_name['name'] == '' ? $class_name['e_name'] : $class_name['name'];

            if ($v['type'] == '1flex') {
                $v['type'] = 'one flex';
            } elseif($v['type'] == 'openflex') {
                $v['type'] = 'open flex';
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $rows
        );
        return json($data);
    }


    //调研分类
    public function cate(Request $request)
    {
        $flex_id = $request->param('id');

        View::assign('flex_id', $flex_id);
        return View::fetch();
    }

    public function getCateList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $total = Db::name('flex_category')
            ->where('flex_id', '=', $get['flex_id'])
            ->count();

        $rows = Db::name('flex_category')
            ->where('flex_id', '=', $get['flex_id'])
            ->order("sort asc, id asc")
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $v['course_total'] = Db::name('flex_course')->where('category_id', '=', $v['id'])->count();

            if ($v['type'] == 1) {
                $v['type_name'] = '普通';
            } else if($v['type'] == 2) {
                $v['type_name'] = '推荐';
            } else {
                $v['type_name'] = '热门';
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function addCate(Request $request)
    {
        $flex_id = $request->param('flex_id');

        View::assign('flex_id', $flex_id);
        return View::fetch();
    }


    //+分类保存
    public function saveCate(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $post = remove_xss($post);
        // 验证
        try {

            validate(CheckCate::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            if ($post['type'] == 2) {
                $count = Db::name('flex_category')
                    ->where('flex_id', '=', $post['flex_id'])
                    ->where('type', '=', $post['type'])
                    ->count();
                if ($count >= 1) {
                    return $this->outputAjax('推荐分类只能创建一个！');
                }
            }

            if ($post['type'] == 3) {
                $count = Db::name('flex_category')
                    ->where('flex_id', '=', $post['flex_id'])
                    ->where('type', '=', $post['type'])
                    ->count();
                if ($count >= 1) {
                    return $this->outputAjax('热门分类只能创建一个！');
                }
            }

            $data = array(
                'flex_id'   => $post['flex_id'],
                'name'      => $post['name'],
                'e_name'    => $post['e_name'],
                'icon'      => $post['icon'],
                'type'      => $post['type'],
                'add_time'  => time(),
            );

            if ($post['type'] == 2 || $post['type'] == 3) {
                $data['sort'] = 0;
            }
            if (!Db::name('flex_category')->insert($data)) {
                return $this->outputAjax('保存失败！');
            }
            return $this->outputAjax('保存成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //+自定义课程分类-编辑
    public function editCate(Request $request)
    {
        $id = $request->get('id');

        $inf = Db::name('flex_category')->find($id);
        View::assign('inf', $inf);
        return View::fetch();
    }

    //+分类保存
    public function modifyCate(Request $request)
    {
        $post = $request->post();

        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCate::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $inf = Db::name('flex_category')->find($post['id']);

            if (!$inf) {
                return $this->outputAjax('参数错误！');
            }

            $update = array(
                'id'        => $post['id'],
                'name'      => $post['name'],
                'e_name'    => $post['e_name'],
                'icon'      => $post['icon'],
                'add_time'  => time(),
            );
            if (!Db::name('flex_category')->update($update)) {
                return $this->outputAjax('保存失败！');
            }
            return $this->outputAjax('保存成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function setCateSort(Request $request)
    {
        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 1 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在1-999之间！');
        }

        Db::startTrans();
        try {
            $res = Db::name('flex_category')->where('id', '=', $post['id'])->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }
            if ($res['type'] == 2 || $res['type'] == 3) {
                return $this->outputAjax('该分类不可修改排序！');
            }

            $rows = Db::name('flex_category')
                ->where('id', '<>', $post['id'])
                ->where('flex_id', '=', $res['flex_id'])
                ->where('sort', '>=', $post['sort'])
                ->where('type', '=', 1)
                ->order('sort asc')
                ->select()->toArray();

            if (!Db::name('flex_category')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('flex_category')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
 * 删除分类数据
 * date: 2019-04-10
 * author: admin
 */
    public function deleteCate(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $id = $post['id'];
        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        Db::startTrans();
        try {
            $res = Db::name('flex_category')->where('id', '=', $id)->value('type');
            if ($res != 1) {
                return $this->outputAjax('热门或推荐分类不可删除！');
            }
            if (!Db::name('flex_category')->where('id', '=', $id)->delete()) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]！');
            }
            $course = Db::name('flex_course')->where('category_id', '=', $id)->select()->toArray();

            if ($course) {
                if (!Db::name('flex_course')->where('category_id', '=', $id)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[2]！');
                }
            }
            Db::commit();

            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function setCateStatus(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        if (!$id = $request->param('id')) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('flex_category')->field('status')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            $update = array(
                'id'=> $id,
                'status'=> $status,
            );
            if(!Db::name('flex_category')->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+分类课程
    public function course(Request $request)
    {
        $cate_id = $request->get('cate_id');
        $flex_id = $request->get('flex_id');

        View::assign('cate_id', $cate_id);
        View::assign('flex_id', $flex_id);
        return View::fetch();
    }


    public function getCateCourseList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $cate_id = $request->get('cate_id');
        $flex_id = $request->get('flex_id');
        $get = $request->get();

        $where = [];
        $where[] = ['category_id', '=', $cate_id];
        $where[] = ['flex_id', '=', $flex_id];

        $total = Db::name('flex_course')
            ->where($where)
            ->count();

        $rows = Db::name('flex_course')
            ->where($where)
            ->order("sort asc, id asc")
            ->field('sort, id as aid, type as course_type, courseid, category_id, flex_id, wait')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $course = Db::name('course')
                ->where('courseid', '=', $v['courseid'])
                ->field('id, seminar, e_seminar, seminar_topic, type, module, english')
                ->find();
            $v['seminar'] = $course['seminar'] == '' ? $course['e_seminar']:$course['seminar'];
            $v['id'] = $course['id'];
            $v['course_type_name'] = get_config('app.course.type', $course['type']);
            $v['module'] = get_config('app.course.module', $course['module']);
            $v['english'] =  $course['english'] == '' ? '':get_config('app.course.english', $course['english']);

            $xw = Db::name('flex_classes')
                ->where('flex_id', '=', $v['flex_id'])
                ->where('courseid', '=', $v['courseid'])
                ->find();
            if ($xw) {
                $selected = Db::name('flex_user_classes')
                    ->where('courseid', '=', $v['courseid'])
                    ->where('flex_id', '=', $v['flex_id'])
                    ->where('class_id', '<>', 0)
                    ->where('status', '=', 1)
                    ->count();
                $seats = Db::name('flex_classes')
                    ->where('courseid', '=', $v['courseid'])
                    ->where('flex_id', '=', $v['flex_id'])
                    ->sum('seats');
                if($seats == 0) {
                    $v['xiwei'] = $selected.'/无限制';
                } else {
                    $seats1 = Db::name('flex_classes')
                        ->where('courseid', '=', $v['courseid'])
                        ->where('flex_id', '=', $v['flex_id'])
                        ->where('seats_type', '=', 0)
                        ->find();
                    if ($seats1) {
                        if ($selected >= $seats) {
                            $v['xiwei'] = $selected.'/无限制';;
                        } else {
                            $v['xiwei'] = $selected.'/无限制';
                        }
                    } else {
                        if ($selected >= $seats) {
                            $v['xiwei'] = '已售罄/'.$seats;;
                        } else {
                            $v['xiwei'] = $selected.'/'.$seats;
                        }
                    }
                }
            } else {
                $v['xiwei'] = '0/0';
            }

            $category_type = Db::name('flex_category')
                ->where('id', '=', $v['category_id'])
                ->value('type');
            $v['cate_type'] = $category_type;
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+选课班级开启OR关闭等候名单
    public function setCateCourseWait(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('flex_course')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['wait'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $wait = $inf['wait'] == 1 ? 2 : 1;

            $where = array(
                'flex_id' => $inf['flex_id'],
                'courseid' => $inf['courseid']
            );
            if(Db::name('flex_course')->where($where)->update(['wait'=>$wait])) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //+课程排序
    public function setCateCourseSort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        Db::startTrans();
        try {
            $res = Db::name('flex_course')->where('id', '=', $post['id'])->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('flex_course')
                ->where('id', '<>', $post['id'])
                ->where('category_id', '=', $res['category_id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort asc')
                ->select()
                ->toArray();

            if (!Db::name('flex_course')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('flex_course')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }

                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function xuanke(Request $request)
    {
        $cate_id = $request->get('cate_id');
        $flex_id = $request->get('flex_id');

        View::assign('cate_id', $cate_id);
        View::assign('flex_id', $flex_id);
        return View::fetch();
    }

    public function getXuankeInfo(Request $request)
    {
        $cate_id = $request->post('cate_id');
        $flex_id = $request->post('flex_id');

        $status = Db::name('flex')->where('id', '=', $flex_id)->value('status');
        if ($status == 1) {
            $flex_id_arr = Db::name('flex')->where('status', '=', 1)->where('id', '<>', $flex_id)->column('id');
        } else {
            $flex_id_arr = [];
        }


        // one flex
        $s = Db::name('flex_course')
            ->where('category_id', '=', $cate_id)
            ->where('type', '=', '1flex')
            ->column('courseid');

        $one_old = Db::name('flex_course')
            ->where('type', '=', '1flex')
            ->whereIn('flex_id', $flex_id_arr)
            ->column('courseid');

        $oneflex = Db::name('course')
            ->where('type', '=', 1)
            ->where('status', '=', 1)
            ->whereNotIn('courseid', $one_old)
            ->field('courseid as value, seminar as title, e_seminar')
            ->order('id', 'desc')
            ->select()
            ->toArray();
        foreach ($oneflex as &$v) {
            if ($v['title'] == '') {
                $v['title'] = $v['e_seminar'];
            }
            unset($v['e_seminar']);

            if (in_array($v['value'], $s)) {
                $v['checked'] = 'checked';
            } else {
                $v['checked'] = '';
            }
        }


        // open flex
        $opens = Db::name('flex_course')
            ->where('category_id', '=', $cate_id)
            ->where('type', '=', 'openflex')
            ->column('courseid');
        $open_old = Db::name('flex_course')
            ->where('type', '=', 'openflex')
            ->whereIn('flex_id', $flex_id_arr)
            ->column('courseid');

        $openflex = Db::name('course')
            ->where('type', '=', 2)
            ->where('status', '=', 1)
            ->whereNotIn('courseid', $open_old)
            ->field('courseid as value, seminar as title, e_seminar')
            ->order('id', 'desc')
            ->select()
            ->toArray();
        foreach ($oneflex as &$v) {
            if ($v['title'] == '') {
                $v['title'] = $v['e_seminar'];
            }
            unset($v['e_seminar']);
        }

        $data = array(
            'oneflex_str' => $s,
            'oneflex' => $oneflex,
            'openflex_str' => $opens,
            'openflex' => $openflex,
        );

        $datas = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $data
        );
        return json($datas);
    }

    //+分类课程保存
    public function saveCourse(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        if (empty($post['cate_id']) || empty($post['type']) || empty($post['flex_id'])) {
            return $this->outputAjax('参数不足！');
        }

        try {
            //找出所有旧的，成功之后删除
            $old = Db::name('flex_course')
                ->where('category_id', '=', $post['cate_id'])
                ->where('type', '=', $post['type'])
                ->column('courseid');

            $temp = [];
            $temp['category_id'] = $post['cate_id'];
            $temp['flex_id'] = $post['flex_id'];
            $temp['type'] = $post['type'];
            if (empty($post['courseid'])) {
                $arr = [];
            } else {
                $arr = $post['courseid'];
            }

            $arr1 = array_diff($old,$arr);
            $arr2 = array_diff($arr,$old);
            if (!empty($arr2)) {
                foreach ($arr2 as $key => $value) {
                    if ($value) {
                        $temp['courseid'] = $value;
                        $temp['add_time'] = time();
                        Db::name('flex_course')->insert($temp);

                        $user = Db::name('course_user')
                            ->where('courseid', '=', $value)
                            ->select()
                            ->toArray();

                        if ($user) {

                            $insert = [];

                            foreach ($user as &$v) {
                                $array = array(
                                    'courseid' => $v['courseid'],
                                    'rules_id' => $v['rules_id'],
                                    'userid' => $v['userid'],
                                    'type' => $v['type'],
                                    'recommend_type' => $v['recommend_type'],
                                    'add_time' => time()
                                );
                                array_push($insert, $array);
                            }

                            Db::name('flex_course_user_'.$post['flex_id'])->insertAll($insert);
                        }
                    }
                }
            }

            //+删除旧课程
            if (!empty($arr1)) {
                Db::name('flex_course')
                    ->where('category_id', '=', $post['cate_id'])
                    ->where('courseid', 'in', $arr1)
                    ->delete();

                Db::name('flex_course_user_'.$post['flex_id'])
                    ->where('courseid', 'in', $arr1)
                    ->delete();
            }
            return $this->outputAjax('选课成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+分类课程
    public function classes(Request $request)
    {
        $cate_id = $request->get('cate_id');
        $flex_id = $request->get('flex_id');
        $courseid = $request->get('courseid');

        View::assign('cate_id', $cate_id);
        View::assign('flex_id', $flex_id);
        View::assign('courseid', $courseid);
        return View::fetch();
    }


    //+选课班级数据加载
    public function getCourseClassesList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $total = Db::name('flex_classes')
            ->where('courseid', '=', $get['courseid'])
            ->where('flex_id', '=', $get['flex_id'])
            ->count();

        $rows = Db::name('flex_classes')
            ->where('courseid', '=', $get['courseid'])
            ->where('flex_id', '=', $get['flex_id'])
            ->order("sort asc, id asc")
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $selected = Db::name('flex_user_classes')
                ->where('courseid', '=', $get['courseid'])
                ->where('flex_id', '=', $get['flex_id'])
                ->where('class_id', '=', $v['id'])
                ->where('status', '=', 1)
                ->count();
            if ($v['seats_type'] == 0) {
                $v['xiwei'] = $selected.'/无限制';
            } else {
                if ($selected >= $v['seats']) {
                    $v['xiwei'] = '已售罄/'.$v['seats'];
                } else {
                    $v['xiwei'] = $selected.'/'.$v['seats'];
                }
            }

        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function setClassesSort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }
        Db::startTrans();
        try {
            $res = Db::name('flex_classes')->where('id', '=', $post['id'])->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }

            $rows = Db::name('flex_classes')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort asc')
                ->select()
                ->toArray();

            if (!Db::name('flex_classes')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('flex_classes')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    //+选课班级-添加
    public function addClasses(Request $request)
    {
        $cate_id = $request->get('cate_id');
        $flex_id = $request->get('flex_id');
        $courseid = $request->get('courseid');

        View::assign('cate_id', $cate_id);
        View::assign('flex_id', $flex_id);
        View::assign('courseid', $courseid);
        return View::fetch();
    }

    //+选课班级保存
    public function saveClasses(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $post = $request->post();

        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckFlexClasses::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }
        if ($post['seats_type'] == 1) {
            if ($post['seats'] < 1) {
                return $this->outputAjax('席位不能小于1');
            }
        }

        try {
            $data = array(
                'courseid'      => $post['courseid'],
                'category_id'   => $post['cate_id'],
                'flex_id'       => $post['flex_id'],
                'name'          => $post['name'],
                'e_name'        => $post['e_name'],
                'class_time'    => $post['class_time'],
                'e_class_time'  => $post['e_class_time'],
                'seats_type'    => $post['seats_type'],
                'seats'         => $post['seats'],
                'add_time'      => time(),
            );

            if (!Db::name('flex_classes')->insert($data)) {
                return $this->outputAjax('保存失败！');
            }
            return $this->outputAjax('保存成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //+选课班级-编辑
    public function editClasses(Request $request)
    {
        $id = $request->get('id');

        $inf = Db::name('flex_classes')->find($id);

        View::assign('inf', $inf);
        return View::fetch();
    }

    //+选课班级保存
    public function modifyClasses(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $post = remove_xss($post);
        // 验证
        try {

            validate(CheckFlexClasses::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $inf = Db::name('flex_classes')->find($post['id']);

            if (!$inf) {
                return $this->outputAjax('参数错误！');
            }

            $update = array(
                'id'            => $post['id'],
                'name'          => $post['name'],
                'e_name'        => $post['e_name'],
                'class_time'    => $post['class_time'],
                'e_class_time'  => $post['e_class_time'],
                'seats_type'    => $post['seats_type'],
                'seats'         => $post['seats'],
                'add_time'  => time(),
            );

            if (!Db::name('flex_classes')->update($update)) {
                return $this->outputAjax('保存失败！');
            }
            return $this->outputAjax('保存成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
     * 删除选课班级
     * date: 2019-04-10
     * author: admin
     */
    public function deleteClasses(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $id = $post['id'];
        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        Db::startTrans();
        try {
            $selected = Db::name('flex_user_classes')
                ->where('class_id', '=', $id)
                ->count();
            if ($selected > 0) {
                Db::rollback();
                return $this->outputAjax('删除失败，班级存在学员！');
            }
            if (!Db::name('flex_classes')->where('id', '=', $id)->delete()) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]！');
            }
            Db::commit();
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }

    }
}